// 运行时配置

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://next.umijs.org/docs/api/runtime-config#getinitialstate

import {
  RunTimeLayoutConfig,
  RequestConfig,
  Outlet,
  history,
} from '@umijs/max';
import type { IRoute } from '@umijs/max';
import { getToken, removeToken } from './utils/auth';
import type { MenuDataItem } from '@ant-design/pro-components';
import { ModalForm, ProForm, ProFormText } from '@ant-design/pro-components';
import { lazy, Suspense, useState } from 'react';
import { message, Breadcrumb, Dropdown, Avatar } from 'antd';
import { AxiosResponse, AxiosError } from '@umijs/max';
import { LogoutOutlined, EditOutlined } from '@ant-design/icons';
import { changePassword } from '@/services/login';
// const Module = (ModuleName: string) => {
//   const Component = lazy(
//     () => import(`@/pages/${ModuleName.replace(/^\//, '')}.tsx`),
//   );
//   return ModuleName ? <Component /> : <Outlet />;
// };
// const handleRoute = (data: Menu.MenuDataItem[]): MenuDataItem[] => {
//   return data.map((item: Menu.MenuDataItem) => {
//     const {
//       meta: { title },
//       children,
//       hidden,
//       path,
//       component,
//     } = item;
//     return {
//       name: title,
//       path,
//       hideInMenu: hidden === 'true',
//       element: <Suspense> {Module(component)}</Suspense>,
//       children: children ? handleRoute(children) : [],
//     };
//   });
// };
// export async function getInitialState() {
//   if (getToken()) {
//     const [PreviewUrl, BaseData] = await Promise.all([
//       getPreviewUrl(),
//       listAllDataInfos(),
//     ]);
//     return {
//       PreviewUrl,
//       BaseData,
//     };
//   }
// }
const authHeaderInterceptor = (url: string, options: RequestConfig) => {
  const { needToken = true } = options;
  const authHeader = { 'X-Base-Token': getToken() };
  return {
    url: `${url}`,
    options: {
      ...options,
      interceptors: true,
      headers: needToken ? authHeader : null,
    },
  };
};
const Modal = (props) => {
  const { open, setOpen } = props;
  return (
    <ModalForm
      title="修改密码"
      modalProps={{
        destroyOnClose: true,
        width: '20%',
        onCancel: () => {
          setOpen(false);
        },
      }}
      open={open}
      onFinish={async (values) => {
        changePassword(values).then(() => {
          message.success('修改成功');
          setOpen(false);
        });
      }}
    >
      <ProFormText.Password
        width="md"
        name="password"
        label="新密码"
        rules={[
          {
            required: true,
            message: '请输入新密码',
          },
        ]}
        placeholder="请输入新密码"
      />
      <ProFormText.Password
        width="md"
        name="rePassword"
        label="确认密码"
        rules={[
          {
            required: true,
            message: '请再次输入新密码',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次密码不匹配！'));
            },
          }),
        ]}
        placeholder="请再次输入新密码"
      />
    </ModalForm>
  );
};
export const layout: RunTimeLayoutConfig = () => {
  return {
    // 常用属性
    title: '活动报名管理系统',
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
    rightContentRender: () => {
      const [open, setOpen] = useState(false);
      return (
        <>
          {/* <Modal open={open} setOpen={setOpen}></Modal>
          <Dropdown
            menu={{
              items: [
                {
                  key: 'changePsd',
                  icon: <EditOutlined />,
                  label: '修改密码',
                },
                {
                  key: 'logout',
                  icon: <LogoutOutlined />,
                  label: '退出登录',
                },
              ],
              onClick: ({ key }) => {
                if (key === 'logout') {
                  removeToken();
                  history.replace('/login');
                } else {
                  setOpen(true);
                }
              },
            }}
          > */}
            <Avatar src="https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg"></Avatar>
          {/* </Dropdown> */}
        </>
      );
    },
    // 其他属性见：https://procomponents.ant.design/components/layout#prolayout
  };
};
let extraRoutes: MenuDataItem[] | undefined;
export function patchClientRoutes({ routes }: { routes: IRoute[] }) {
  routes
    .find((item) => item.path === '/')
    ?.routes.unshift(...(extraRoutes ?? []));
}

// export async function render(oldRender: () => void) {
//   if (getToken()) {
//     const data = await listMenuShow({ menuType: 'MENU' });
//     extraRoutes = handleRoute(data);
//   }
//   oldRender();
// }
// export function onRouteChange({ location }: { location: Location }) {
//   if (getToken() && location.pathname.includes('login')) {
//     history.go(-1);
//   }
// }
interface ResponseStructure {
  data?: any;
  code: number;
  message: string;
}

export const request: RequestConfig = {
  // errorHandler,
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [authHeaderInterceptor],
  timeout: 10000,
  responseInterceptors: [
    // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
    [
      (response) => {
        const {
          data: { code, message: msg },
        } = response as unknown as AxiosResponse<ResponseStructure>;

        if (code !== 200) {
          message.error(msg);
          if (code === 401) {
            removeToken();
            location.reload();
          }
          return Promise.reject(msg);
        } else {
          return response.data as any;
        }
      },
      (error: AxiosError<any> | Error) => {
        return Promise.reject(
          message.error(
            'message' in error
              ? error.message
              : (error as AxiosError<any>).response?.data.msg,
          ),
        );
      },
    ],
  ],
  baseURL: '/back',
};
